//index.js
const app = getApp()
const db = wx.cloud.database()

Page({
  data: {
    userInfo: {},
    logged: false,
    goods_list: [],
    navbar: ['全部', '图书', '数码','生活','化妆品'],
    currentTab: 0,
    searchConponent:"",
    goodsObjects:[],
  },

  onLoad: function() {
    //加载登录信息，调用云函数
    if(1){
      wx.cloud.callFunction({
        name:"userLogin",
      }).then(res=>{
        console.log('登录校验调用成功')
      })
    }
  },

  //获取商品信息
  getGoods(){
    var that = this
    db.collection("goods").get({
      success: function(res) {
        //console.log(res)
        that.setData({
          goodsObjects : res.data,
        })
      }
    })
  },

  //获取商品数据
  onReady: function () {
    this.getGoods()
  },
  
  //点击分类框
  navbarTap: function(e){
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    this.changeData(e.currentTarget.dataset.idx)
  },

  //改变显示
  changeData:function(index){
    var that = this
    if(index==0){
      this.getGoods()
      return
    }
    db.collection("goods").where({
      type: that.data.navbar[index]
    }).get({
      success: function(res) {
        //console.log(res)
        that.setData({
          goodsObjects : res.data,
        })
      }
    })
  },


  //获取搜索框内容
  getSearchConponent:function(e){
    this.setData({
      searchConponent: e.detail.value
    })
    console.log("searchConponent is " + this.data.searchConponent)
  },

  //处理搜索框内容
  sendText(e){
    this.setData({
      searchConponent: e.detail.value
    })
    console.log("send txt is " + this.data.searchConponent)
    wx.redirectTo({
      url: '../../pages/search/search?text='+this.data.searchConponent,
    })
  },

  //下拉刷新
  onPullDownRefresh: function() {
    wx.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    })
    this.updatePage()
  },

  //重新渲染界面
  updatePage: function () {
    this.getGoods()
  },
})
